class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  //编译模版，处理文本节点和元素节点
  compile(el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      //判断元素节点和文本节点,对应进行处理
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }
      //递归调用子节点进行处理
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  //编译元素节点，处理指令
  compileElement(node) {
    //遍历所有属性节点,找到所有指令
    Array.from(node.attributes).forEach(attr => {
      //判断是否是指令
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        const key = attr.value
        //处理
        if (attrName.startsWith('@')) {
          this.onUpdater(node, key, attrName.substr(1))
        } else if (attrName.startsWith('v-on')) {
          this.onUpdater(node, key, attrName.substr(5))
        } else {
          // 处理不同的指令(node,key值，属性名v-xxx)
          this.update(node, key, attrName.substr(2))
        }
      }
    })
  }
  update(node, key, dir) {
    // node 节点，key 数据的属性名称，dir 指令的后半部分
    const updaterFn = this[dir + 'Updater']
    updaterFn && updaterFn.call(this, node, this.vm[key], key)
  }
  //v-on处理
  onUpdater(node, key, eventType) {
    node.addEventListener(eventType, () => {
      this.vm.$options.methods[key].call(this.vm)
    }, false)
  }
  // v-html 指令
  htmlUpdater(node, value, key) {
    node.innerHTML = value;
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue;
    })
  }
  //v-text处理
  textUpdater(node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  //v-model处理
  modelUpdater(node, value, key) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    //双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  //编译文本节点
  compileText(node) {
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      //更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  //判断元素属性是否是指令
  isDirective(attrName) {
    return attrName.startsWith('v-') || attrName.startsWith('@')
  }
  // 判断是否是文本节点 
  isTextNode(node) {
    return node.nodeType === 3
  }
  // 判断是否是属性节点 
  isElementNode(node) {
    return node.nodeType === 1
  }
}